// pages/share/add/index.js
const app = getApp()
const db = wx.cloud.database()
const _ = db.command


Page({

    /**
     * 页面的初始数据
     */
    data: {
        imgbox:"",
        array: ['请选择动物类别','猪类', '牛类', '羊类', '马类','驴类','禽类','其他类'],
        currentChoose: 0,
        fileIDs:[],
        openid:''
    },

    toback() {
        wx.navigateBack({
          delta: 0,
          success: (res) => {},
          fail: (res) => {},
          complete: (res) => {},
        })
    },

    bindPickerChange: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
          currentChoose: e.detail.value
        })
      },

    getInputValue(event){
        console.log("输入的内容", event.detail.value)
        this.setData({
            title: event.detail.value
        })
    },

    getInput(event) {
        console.log("输入的内容", event.detail.value)
        var str = event.detail.value.split('&hc').join('\n');
        console.log("输入的", str)
        this.setData({
            desc: str
        })
    },
      // 删除照片 &&
    imgDelete1: function (e) {
        let that = this;
        let index = e.currentTarget.dataset.deindex;
        let imgbox = this.data.imgbox;
        imgbox.splice(index, 1)
        that.setData({
            imgbox: imgbox
        });
    },

    addPic1: function (e) {
        var imgbox = this.data.imgbox;
        console.log(imgbox)
        var that = this;
        var n = 9;
        if (9 > imgbox.length > 0) {
            n = 9 - imgbox.length;
        } else if (imgbox.length == 9) {
            n = 1;
        }
        wx.chooseImage({
            count: n, // 默认9，设置图片张数
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
            // console.log(res.tempFilePaths)
            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
            var tempFilePaths = res.tempFilePaths
            if (imgbox.length == 0) {
                imgbox = tempFilePaths
            } else if (9 > imgbox.length) {
                imgbox = imgbox.concat(tempFilePaths);
            }
            that.setData({
                imgbox: imgbox
            });
            }
        })
    },
    
    //图片
    imgbox: function (e) {
        this.setData({
            imgbox: e.detail.value
        })
    },

    fb() {
       
        let that = this
        let desc = this.data.desc
        let title = this.data.title
        let attribute = this.data.array[this.data.currentChoose]
        let imgbox = this.data.imgbox
        let seg='hello '+desc+title//因为空串检测后返回结果是不通过，所以强行让seg为非空串
        
        wx.cloud.callFunction({
            name:"checkMsg",//云函数名称,敏感词检测
            data:{
              msg:seg//需要检查的字符串
            },success(res){//检查通过
              console.log("检查通过");

              if (!desc || desc.length < 0 ||!title ||title.length < 0) {
                wx.showToast({
                icon: "none",
                title: '请输入内容和标题'
                })
                return
            }
            
            if (that.data.currentChoose == 0) {
                wx.showToast({
                icon: "none",
                title: '请选择类别'
                })
                return
            }
            if (!imgbox || imgbox.length < 1) {
                wx.showToast({
                icon: "none",
                title: '请选择图片'
                })
                return
            }
            wx.showLoading({
                title: '发布中...',
            })
            let promiseArr = [];
            for (let i = 0; i < that.data.imgbox.length; i++) {
            promiseArr.push(new Promise((reslove, reject) => {
                let item = that.data.imgbox[i];
                let suffix = /\.\w+$/.exec(item)[0]; //正则表达式返回文件的扩展名
                wx.cloud.uploadFile({
                cloudPath: new Date().getTime() + suffix, // 上传至云端的路径
                filePath: item, // 小程序临时文件路径
                }).then(res => {
                console.log("上传结果", res.fileID)
                that.setData({
                    fileIDs: that.data.fileIDs.concat(res.fileID)
                })
                reslove()
                }).catch(error=>{
                console.log("上传失败",error);
                })
            }))
            }
            Promise.all(promiseArr).then(res => {
           // let that = this
            if(that.data.city == "获取"){
                that.setData({
                city: ""
                })
            }
            wx.cloud.database().collection('share').add({
                data: {
                    title: title,
                    fileIDs: that.data.fileIDs,
                    date: that.getNowFormatDate(),
                    createTime: db.serverDate(),
                    desc: that.data.desc,
                    attribute: attribute,
                    avatarUrl:app.globalData.userInfo.avatarUrl,//头像
                    nickName:app.globalData.userInfo.nickName,//名称
                    isTouchMove: false
                },
                success: res => {
                wx.hideLoading()
                wx.showToast({
                    title: '发布成功',
                })
                console.log('发布成功', res)
                wx.reLaunch({
                  url: '../myshare/index',
                })
                },
                fail: err => {
                wx.hideLoading()
                wx.showToast({
                    icon: 'none',
                    title: '网络不给力....'
                })
                console.error('发布失败', err)
                }
                
            })
            })
            Promise.all(promiseArr).then(res => {//等数组都做完后做then方法
            console.log("图片上传完成后再执行")
            that.setData({
                imgbox:[],
            })
            })

            },fail(res){//检查未通过
                console.log(res);
              console.log("检查未通过");
              wx.showToast({
                title: '您的文章中存在敏感词汇，请改正后再发布!',
                icon: 'none',
                duration: 3000
              })  
              /*that.setData({
                seg_pass:false
            });*/
            }
          })
    }, 
    getNowFormatDate: function () {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
          month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
          strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
          " " + date.getHours() + seperator2 + date.getMinutes() +
          seperator2 + date.getSeconds();
        return currentdate;
      },
    
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {


    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})